package com.pai4j.pgc.service.resource.convert;
import com.pai4j.common.util.FileConvertUtil;
import com.pai4j.domain.community.vo.response.resource.ResourceConvertBufferImageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.xhtmlrenderer.simple.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * PDF转图片
 *
 * @author: CYM-pai
 * @date: 2025/10/27 17:33
 **/
@Slf4j
public class PDFResourceConvertImageService extends AbstractResourceConvertImageService {

    public PDFResourceConvertImageService() {

    }

    /***
     * 其他Office文档先转PDF，优先pdfByte
     */
    public PDFResourceConvertImageService(String pdfPath) {
        super.file = new File(pdfPath);
    }

    @Override
    public ResourceConvertBufferImageResult doProcess() {

        int allPageCount = 0;

        List<BufferedImage> bufferedImageList = new ArrayList<>();
        ByteArrayOutputStream byteArrayOutputStream = null;
        PDDocument doc = null;
        try {
            byte[] pdfByte = FileConvertUtil.convertMultipartFileToByteArray(
                        FileConvertUtil.convertFileToMultipartFile(this.file));
            // 将pdf转图片 并且自定义图片得格式大小
            byteArrayOutputStream = new ByteArrayOutputStream();
            doc = PDDocument.load(pdfByte);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            allPageCount = pageCount;
            if (maxImageCount != -1 && maxImageCount < pageCount) {
                // 限制转换图片张数
                pageCount = maxImageCount;
            }
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, DEFAULT_IMAGE_DPI);
                ImageIO.write(image, DEFAULT_IMG_EXT, byteArrayOutputStream);
                bufferedImageList.add(image);
                log.info("PDF完成第{}页转换，共{}页.", i + 1, pageCount);
            }
        } catch (Exception e) {
            log.error("PDF转图片失败.", e);
        } finally {
            if (this.file.exists()) {
                // 删除本地文件
                file.delete();
            }
            try {
                doc.close();
            } catch (IOException e) {
                log.error("doc关闭失败.", e);
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    log.error("PDF转图片字节流关闭失败.", e);
                }
            }
        }
        return new ResourceConvertBufferImageResult(allPageCount, bufferedImageList);
    }
}
